package com.base.camera

import android.content.Context
import android.hardware.camera2.CameraCaptureSession
import android.hardware.camera2.CameraDevice
import android.hardware.camera2.CameraManager
import android.view.Surface
import androidx.annotation.IntRange
import androidx.annotation.RequiresPermission


class CameraHelp constructor(private val context: Context){
    private val manager by lazy { context.getSystemService(Context.CAMERA_SERVICE) as CameraManager }
    private var cameraId: String? = null
    private var camera: CameraDevice? =  null
    private var call: Call? = null
    private val sessionList = mutableListOf<CameraCaptureSession>()

    @RequiresPermission(android.Manifest.permission.CAMERA)
    fun open(@IntRange(from = 0,to = 1)id: Int){
        cameraId =  id.toString()
        camera?.close()
        manager.openCamera(id.toString(),object: CameraDevice.StateCallback(){
            override fun onOpened(camera: CameraDevice) {
                this@CameraHelp.camera = camera
                call?.open(camera)
            }

            override fun onDisconnected(camera: CameraDevice) {
                call?.disconnected(camera)
                this@CameraHelp.camera = null
            }

            override fun onError(camera: CameraDevice, error: Int) {
                call?.cameraError(camera,error)
                this@CameraHelp.camera = null
            }
        },null)
    }

    fun createSession(outputs: MutableList<Surface>,camera: CameraDevice = this.camera!!){
        camera.createCaptureSession(outputs,object: CameraCaptureSession.StateCallback(){
            override fun onConfigured(session: CameraCaptureSession) {
                sessionList.add(session)

            }

            override fun onConfigureFailed(session: CameraCaptureSession) {
                sessionList.remove(session)
                session.close()
            }

            override fun onActive(session: CameraCaptureSession) {

            }

            override fun onCaptureQueueEmpty(session: CameraCaptureSession) {

            }

            override fun onClosed(session: CameraCaptureSession) {
                sessionList.remove(session)
            }

            override fun onReady(session: CameraCaptureSession) {}

            override fun onSurfacePrepared(session: CameraCaptureSession, surface: Surface) {

            }

        },null)
    }



    interface Call{
        fun open(camera: CameraDevice)
        fun cameraError(camera: CameraDevice, error: Int)
        fun disconnected(camera: CameraDevice)
    }


}